<template>
  <div class="home-container">
    <el-row :gutter="10">
      <el-col :span="12">
        <div class="pdf-container" v-loading="pdfLoading">
          <div class="container-head">
            <div class="control-panel">
              <!-- 保留控制栏但禁用缩放按钮，因为iframe由浏览器控制缩放 -->
              <div class="zoom-controls">
                <!-- <el-button-group>
                    <el-button :icon="ZoomIn" size="small" title="放大" disabled></el-button>
                    <el-button :icon="ZoomOut" size="small" title="缩小" disabled></el-button>
                    <el-button :icon="Refresh" @click="refreshPdf" size="small" title="刷新"></el-button>
                </el-button-group> -->
                <span class="zoom-level">浏览器默认</span>
              </div>
              <div class="page-controls">
                <!-- 页码显示依然保留，但翻页功能由iframe的PDF查看器控制 -->
                <span class="page-display">由浏览器PDF查看器控制</span>
              </div>
            </div>
          </div>
          <div class="container-body">
            <div class="pdf-viewer">
              <!-- 使用iframe替代canvas加载PDF -->
              <iframe 
                ref="pdfIframe"
                :src="pdf1Url" 
                class="pdf-iframe" 
                frameborder="0"
                title="PDF文档"
                loading="lazy"
                @load="handlePdfLoaded"
              ></iframe>
            </div>
          </div>
      </div>
      </el-col>
      <el-col :span="12">
        <div class="markdown-container" v-loading="markdownLoading">
          <el-tabs
            v-model="activeName"
            class="demo-tabs"
            @tab-change="handleChange"
          >
            <el-tab-pane>
              <template #label>
                <span class="container-head">
                  <el-icon class="head-icon"><Reading /></el-icon>
                  <span style="margin-left: 30px; font-weight: 500;">文档洞察</span>
                </span>
              </template>
              <div class="container-body">
                <div class="markdown-body" v-html="renderedMarkdown"></div>
              </div>
            </el-tab-pane>
            <el-tab-pane>
              <template #label>
                <span class="container-head">
                  <el-icon class="head-icon"><ChatDotSquare /></el-icon>
                  <span style="margin-left: 30px; font-weight: 500;">文档问答</span>
                </span>
              </template>
              <div class="container-body">
                <div class="message-container" ref="scrollContainer">
                  <div style="display: flex; flex-direction: column">
                    <div
                      v-for="(item, index) in messageList"
                      :key="index"
                      :class="item.role == 'user' ? 'answer-msg' : 'question-msg'"
                    >
                      <div v-if="item.role == 'robot'">
                        <svg style="display: inline" width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="text-foreground"><circle cx="4" cy="12" r="2" fill="currentColor"><animate id="spinner_qFRN" begin="0;spinner_OcgL.end+0.25s" attributeName="cy" calcMode="spline" dur="0.6s" values="12;6;12" keySplines=".33,.66,.66,1;.33,0,.66,.33"></animate></circle><circle cx="12" cy="12" r="2" fill="currentColor"><animate begin="spinner_qFRN.begin+0.1s" attributeName="cy" calcMode="spline" dur="0.6s" values="12;6;12" keySplines=".33,.66,.66,1;.33,0,.66,.33"></animate></circle><circle cx="20" cy="12" r="2" fill="currentColor"><animate id="spinner_OcgL" begin="spinner_qFRN.begin+0.2s" attributeName="cy" calcMode="spline" dur="0.6s" values="12;6;12" keySplines=".33,.66,.66,1;.33,0,.66,.33"></animate></circle></svg>
                        {{item.content}}
                      </div>
                      <div v-else v-html="renderMarkdown(item.content)"></div>
                    </div>
                  </div>
                </div>
                <div class="input-container">
                  <div class="input-border">
                    <el-input class="message-input" v-model="answer" placeholder="尽管问..." type="textarea" @keyup.enter="answerSubmit" />
                    <div style="padding-right: 10px">
                      <el-button type="primary" @click="answerSubmit" class="message-btn" :disabled="!answer || answerStatus == 1">
                        <svg v-if="answerStatus == 1" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader-circle animate-spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"></path></svg>
                        <span style="margin: 0 10px">发送</span>
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-corner-down-left size-3.5"><polyline points="9 10 4 15 9 20"></polyline><path d="M20 4v7a4 4 0 0 1-4 4H4"></path></svg>
                      </el-button>
                      <el-select class="model-select" v-model="optionsVal" placeholder="请选择模式">
                        <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                        </el-option>
                      </el-select>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>
  </div>
    
</template>

<script setup>
import { Reading, ZoomIn, ZoomOut, Refresh } from '@element-plus/icons-vue'
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { analyzeStatus, chatSend, chatHistory } from '@/api/user';
import { marked } from 'marked';

const route = useRoute();
const pdfLoading = ref(true);
const markdownLoading = ref(true);

const activeName = ref('0')
// 注释掉pdfjs-lib相关代码
/*
import * as pdfjsLib from 'pdfjs-dist/build/pdf.min.mjs'

pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
    'pdfjs-dist/build/pdf.worker.mjs',
    import.meta.url
).toString()
*/

const pdf1Url = ref('')
// 保留这些变量以兼容现有逻辑，但大部分功能不再使用
const page1 = ref(1)
const pdf1TotalPages = ref(1)

// 替换canvas引用为iframe引用
const pdfIframe = ref(null)
const leftPdfViewer = ref(null)

const options = ref([
  {
    value: 0,
    label: '基础模式：0.5积分/次'
  },
  {
    value: 1,
    label: '进阶模式：2积分/次'
  },
  {
    value: 2,
    label: '深度模式：4积分/次'
  }
]);
const optionsVal = ref(0);
const answer = ref('');
const answerStatus = ref(0); // 0 不在问答中  1 问答中 
const messageList = ref([]);

const scrollContainer = ref(null);
// 注释掉PDF渲染相关的变量
/*
let pdf1Instance = null
let pdf1RenderPromise = Promise.resolve();
// 缩放控制相关
const zoomLevels = ref({
    left: 2.0,
    right: 2.0
})
const defaultZoom = 2.0
const minZoom = 0.5
const maxZoom = 3.0
const zoomStep = 0.25
const connectionOffset = ref({ left: 5, right: -5 })
const isRendering1 = ref(false)
*/

const markdownContent = ref('');
const taskId = ref('');

// 配置marked选项，确保正确处理换行和GFM
marked.setOptions({
  breaks: true,
  gfm: true,
  headerIds: true,
  mangle: false,
  sanitize: false,
  smartLists: true,
  smartypants: true
});

// 计算属性，将Markdown内容渲染为HTML
// 修复计算属性定义，computed不应接受参数
const renderedMarkdown = computed(() => {
  if (!markdownContent.value) return '';
  try {
    // 处理转义字符
    let decodedContent = markdownContent.value
      .replace(/\\n/g, '\n')
      .replace(/\\r/g, '\r')
      .replace(/\\t/g, '\t')
      .replace(/\\"/g, '"')
      .replace(/\\'/g, "'")
      .replace(/\\\\/g, '\\')
      .replace(/\\u003c/g, '<')
      .replace(/\\u003e/g, '>')
      .replace(/\\u0026/g, '&');
    return marked(decodedContent);
  } catch (error) {
    console.error('Markdown渲染错误:', error);
    return '<p>Markdown渲染失败</p>';
  }
});

// 添加一个方法用于在模板中直接渲染Markdown并处理转义字符
const renderMarkdown = (content) => {
  if (!content) return '';
  try {
    // 处理转义字符
    let decodedContent = content
      .replace(/\\n/g, '\n')
      .replace(/\\r/g, '\r')
      .replace(/\\t/g, '\t')
      .replace(/\\"/g, '"')
      .replace(/\\'/g, "'")
      .replace(/\\\\/g, '\\')
      .replace(/\\u003c/g, '<')
      .replace(/\\u003e/g, '>')
      .replace(/\\u0026/g, '&');
    return marked(decodedContent);
  } catch (error) {
    console.error('Markdown渲染错误:', error);
    return content; // 失败时返回原始内容
  }
};

onMounted(async () => {
  taskId.value = route.query.task;
  getAnalyzeStatus();
  getChatHistory();
});

const getChatHistory = async () => {
  let res = await chatHistory(taskId.value)
  if (res.code == 200) {
    messageList.value = res.data;
  } else {
    messageList.value = [];
  }
}

const answerSubmit = async () => {
  answerStatus.value = 1;
  const info = answer.value;
  answer.value = '';
  messageList.value.push({
    content: info,
    role: 'user'
  },{
    content: '正在深度思考...',
    role: 'robot'
  });
  nextTick(() => {
    scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
  });
  const params = {
    taskId: taskId.value,
    content: info,
    modelType: optionsVal.value
  }
  try {
    let res = await chatSend(params);
    if (res.code == 200) {
    answerStatus.value = 0;
    messageList.value.pop();
    messageList.value.push({
      content: res.data,
      role: 'assistant'
    })
    nextTick(() => {
      scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
    });
  } else {
    answerStatus.value = 0;
    messageList.value.pop();
    messageList.value.push({
      content: '出错了，请重新提问',
      role: 'assistant'
    })
    nextTick(() => {
      scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
    });
  }
  } catch (error) {
    answerStatus.value = 0;
    messageList.value.pop();
    messageList.value.push({
      content: '出错了，请重新提问',
      role: 'assistant'
    })
    nextTick(() => {
      scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
    });
  }
}

const handleChange = (e) => {
  if (e == 1) {
    nextTick(() => {
      scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
    });
  }
}

// 处理PDF加载完成事件
function handlePdfLoaded() {
  pdfLoading.value = false;
  console.log('PDF通过iframe加载完成');
}

// 刷新PDF
function refreshPdf() {
  if (pdfIframe.value) {
    pdfLoading.value = true;
    pdfIframe.value.src = pdf1Url.value;
  }
}

const getAnalyzeStatus = async ()=>{
  let res = await analyzeStatus(taskId.value)
  if(res.code == 200){
    // 直接使用返回的数据作为Markdown内容
    markdownContent.value = res.data.result;
    markdownLoading.value = false;

    // 设置PDF URL，iframe会自动加载
    pdf1Url.value = res.data.filePath;
    
    // 注释掉PDF.js相关的加载逻辑
    /*
    const loadingTask = pdfjsLib.getDocument(pdf1Url.value)
    pdf1Instance = await loadingTask.promise
    pdf1TotalPages.value = pdf1Instance.numPages
    await loadAndRenderPdf(page1.value)
    */
    
    // 由于iframe是异步加载的，我们不在这里设置loading为false，而是在iframe的onload事件中设置
    console.log('已设置PDF URL:', pdf1Url.value);
  }
}

// 注释掉不再需要的PDF处理函数
/*
async function zoomIn(pdfSide) {
    if (zoomLevels.value.left < maxZoom) {
        zoomLevels.value.left = Math.min(zoomLevels.value.left + zoomStep, maxZoom);
        await loadAndRenderPdf(page1.value, zoomLevels.value.left);
    }
}

async function zoomOut(pdfSide) {
    if (zoomLevels.value.left > minZoom) {
        zoomLevels.value.left = Math.max(zoomLevels.value.left - zoomStep, minZoom);
        await loadAndRenderPdf(page1.value, zoomLevels.value.left);
    }
}

async function resetZoom(pdfSide) {
    zoomLevels.value.left = defaultZoom;
    await loadAndRenderPdf(page1.value, zoomLevels.value.left);
}

async function prevPage(type) {
    if (isRendering1.value) return;
    if (page1.value > 1) {
        page1.value--
        await loadAndRenderPdf(page1.value)
    }
}

async function nextPage(type) {
    if (isRendering1.value) return;
    if (page1.value < pdf1TotalPages.value) {
        page1.value++
        await loadAndRenderPdf(page1.value)
    }
}

async function loadAndRenderPdf(pageNum = 1, zoom = null) {
    if (!pdf1Instance || isRendering1.value) return;
    isRendering1.value = true;
    try {
        await pdf1RenderPromise;
        
        const actualZoom = zoom !== null ? zoom : zoomLevels.value.left;
        
        const page = await pdf1Instance.getPage(pageNum);
        const dpr = window.devicePixelRatio || 1;
        const viewport = page.getViewport({ scale: actualZoom });
        const canvas = pdfCanvas.value;
        const context = canvas.getContext('2d');
        canvas.width = viewport.width * dpr;
        canvas.height = viewport.height * dpr;
        canvas.style.width = `${viewport.width}px`;
        canvas.style.height = `${viewport.height}px`;
        context.setTransform(dpr, 0, 0, dpr, 0, 0);
        pdf1RenderPromise = page.render({
            canvasContext: context,
            viewport: viewport
        }).promise;
        await pdf1RenderPromise;
    } finally {
        isRendering1.value = false;
    }
}
*/
</script>

<style scoped>
.home-container {
  padding: 10px;
  height: 100%;
}
::v-deep .el-row, ::v-deep .el-col {
  height: 100%;
}
.pdf-container, .markdown-container {
    height: 100%;
    border-radius: 10px;
    border: 1px solid #ddd;
    overflow: hidden;
    background: #fff;
}

.container-head {
  height: 47px;
  line-height: 47px;
  padding: 0 20px;
  border-radius: 10px 10px 0 0;
  /* background: oklch(98.5% 0 0); */
  border-bottom: 1px solid #ddd;
  position: relative;
}
::v-deep .el-tabs__item {
  height: 50px;
  padding: 0;
}
::v-deep .el-tabs__item.is-active, ::v-deep .el-tabs__item:hover {
  color: #303133;
}
::v-deep .el-tabs, ::v-deep .el-tab-pane {
  height: 100%;
}
::v-deep .el-tabs__content {
  height: calc(100% - 64px);
}
.container-body {
  height: 100%;
  overflow: auto;
  padding: 0; /* 移除内边距，让iframe充满整个容器 */
  background: #fff;
  display: flex;
  flex-direction: column;
}
.message-container {
  flex: 1;
  padding: 0 16px 16px 16px;
  overflow-y: auto;
}
.input-container {
  height: 110px;
  padding: 0 8px 8px 8px;
  box-sizing: border-box;
}
.input-border {
  border-radius: 10px;
  border: 1px solid oklch(.92 .004 286.32);
  padding: 4px;
  height: 100%;
}
.message-btn {
  padding: 8px;
  margin-top: 4px;
  float: right;
}
.answer-msg {
  align-self: flex-end;
  background: oklch(.967 .001 286.375);
  padding: 8px;
  border-radius: 10px 10px 0 10px;
  max-width: 80%;
  margin-bottom: 14px;
}
.question-msg {
  align-self: flex-start;
  background: rgb(236, 245, 255);
  padding: 8px;
  border-radius: 10px 10px 10px 0;
  max-width: 80%;
  margin-bottom: 14px;
}
.model-select {
  width: 112px;
  height: 33px;
  float: right;
  border-radius: 6px;
  margin-right: 20px;
  margin-top: 4px;
}
::v-deep .el-select__wrapper {
  height: 33px;
  border-radius: 6px;
}
::v-deep .el-button.is-disabled,::v-deep .el-button.is-disabled:hover {
  pointer-events:none
}
::v-deep .el-textarea__inner {
  height: 48px;
  resize: none;
  box-shadow: none;
}
.pdf-viewer {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  min-height: 100%;
  height: 100%; /* 确保充满容器 */
}

/* 为iframe添加样式 */
.pdf-iframe {
  width: 100%;
  height: 100%;
  border: none;
  background-color: white;
}

/* 保留canvas样式但可能不再使用 */
.pdf-canvas {
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
}

.control-panel {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.zoom-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.zoom-level, .page-display {
  font-size: 14px;
  color: #606266;
  min-width: 50px;
  text-align: center;
}

.head-icon {
  font-size: 20px;
  color: #606266;
  position: absolute;
  left: 20px;
  top: 50%;
  margin-top: -9px;
}

/* Markdown样式 - 使用更高优先级确保样式应用 */
:deep(.markdown-body) {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Arial, 'Noto Sans', sans-serif;
  font-size: 16px;
  line-height: 1.6;
  color: #24292e;
  word-wrap: break-word;
}

:deep(.markdown-body h1),
:deep(.markdown-body h2),
:deep(.markdown-body h3),
:deep(.markdown-body h4),
:deep(.markdown-body h5),
:deep(.markdown-body h6) {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

:deep(.markdown-body h1) {
  padding-bottom: 0.3em;
  font-size: 2em;
  border-bottom: 1px solid #eaecef;
}

:deep(.markdown-body h2) {
  padding-bottom: 0.3em;
  font-size: 1.5em;
  border-bottom: 1px solid #eaecef;
}

:deep(.markdown-body h3) {
  font-size: 1.25em;
}

:deep(.markdown-body h4) {
  font-size: 1em;
}

:deep(.markdown-body h5) {
  font-size: 0.875em;
}

:deep(.markdown-body h6) {
  font-size: 0.85em;
  color: #6a737d;
}

:deep(.markdown-body p) {
  margin-top: 0;
  margin-bottom: 16px;
  white-space: pre-wrap;
}

:deep(.markdown-body a) {
  color: #0366d6;
  text-decoration: none;
}

:deep(.markdown-body a:hover) {
  text-decoration: underline;
}

:deep(.markdown-body code) {
  padding: 0.2em 0.4em;
  margin: 0;
  font-size: 85%;
  background-color: rgba(27,31,35,0.05);
  border-radius: 3px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
}

:deep(.markdown-body pre) {
  padding: 16px;
  overflow: auto;
  font-size: 85%;
  line-height: 1.45;
  background-color: #f6f8fa;
  border-radius: 3px;
}

:deep(.markdown-body pre code) {
  padding: 0;
  margin: 0;
  font-size: 100%;
  word-break: normal;
  white-space: pre;
  background: transparent;
  border: 0;
}

:deep(.markdown-body ul),
:deep(.markdown-body ol) {
  padding-left: 2em;
  margin-top: 0;
  margin-bottom: 16px;
}

:deep(.markdown-body ul ul),
:deep(.markdown-body ul ol),
:deep(.markdown-body ol ul),
:deep(.markdown-body ol ol) {
  margin-top: 0;
  margin-bottom: 0;
}

:deep(.markdown-body li) {
  margin-bottom: 0.25em;
}

:deep(.markdown-body table) {
  display: block;
  width: 100%;
  overflow: auto;
  border-spacing: 0;
  border-collapse: collapse;
  margin-bottom: 16px;
}

:deep(.markdown-body table th) {
  font-weight: 600;
}

:deep(.markdown-body table th),
:deep(.markdown-body table td) {
  padding: 6px 13px;
  border: 1px solid #ddd;
}

:deep(.markdown-body table tr) {
  background-color: #fff;
  border-top: 1px solid #ccc;
}

:deep(.markdown-body table tr:nth-child(2n)) {
  background-color: #f8f8f8;
}

:deep(.markdown-body blockquote) {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
  margin: 0 0 16px 0;
}

:deep(.markdown-body img) {
  max-width: 100%;
  box-sizing: content-box;
  background-color: #fff;
}

/* 确保段落中的换行正确显示 */
:deep(.markdown-body p) {
  white-space: pre-wrap;
  word-break: break-word;
}

/* 修复可能的样式覆盖问题 */
:deep(.markdown-body) {
  all: initial !important;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Arial, 'Noto Sans', sans-serif !important;
  font-size: 16px !important;
  line-height: 1.6 !important;
  color: #24292e !important;
  word-wrap: break-word !important;
}
</style>